package com.huiminpay.merchant.controller;



import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.common.cache.util.QRCodeUtil;
import com.huiminpay.merchant.api.IMerchantService;
import com.huiminpay.merchant.api.IStaffService;
import com.huiminpay.merchant.api.IStoreService;
import com.huiminpay.merchant.common.SecurityUtil;
import com.huiminpay.merchant.covert.MerchantCovert;
import com.huiminpay.merchant.dto.MerchantDTO;
import com.huiminpay.merchant.dto.QueryStoreDTO;
import com.huiminpay.merchant.dto.StaffDTO;
import com.huiminpay.merchant.dto.StoreDTO;
import com.huiminpay.merchant.service.IFileHandler;
import com.huiminpay.merchant.service.ISmsService;
import com.huiminpay.merchant.vo.MerchantRegisterVo;
import com.huiminpay.merchant.vo.MerchantVo;
import com.huiminpay.merchant.vo.StaffVo;
import com.huiminpay.merchant.vo.StoreVo;
import com.huiminpay.transaction.api.ITransactionService;
import com.huiminpay.transaction.dto.QRCodeDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@RestController
@Api(value = "商户信息", description = "商户的详细操作", tags = {"商户接口"})
public class MerchantController {

    @org.apache.dubbo.config.annotation.Reference
    IMerchantService merchantService;

    @Autowired
    ISmsService iSmsService;

    @Autowired
    IFileHandler iFileHandler;

    @org.apache.dubbo.config.annotation.Reference
    IStoreService storeService;

    @org.apache.dubbo.config.annotation.Reference
    ITransactionService transactionService;

    @Reference
    IStaffService iStaffService;

    @ApiOperation("ID查询商户信息")
    @ApiImplicitParam(name = "id", value = "商户ID",
            required = true, dataType = "Long",paramType = "path")
    @GetMapping("/merchants/{id}")
    public MerchantRegisterVo queryMerchantById(@PathVariable("id") Long id) {
        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);
        MerchantRegisterVo merchantRegisterVo = MerchantCovert.INSTANCE.dto2regMvo(merchantDTO);
        return merchantRegisterVo;
    }

    @ApiOperation("获取登录用户的商户信息")
    @GetMapping(value="/my/merchants")
    public MerchantVo getMyMerchantInfo(){
        // 从token 中获取商户id
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchantDTO = merchantService.queryMerchantById(merchantId);
        return MerchantCovert.INSTANCE.dto2vo(merchantDTO);

    }


    @ApiOperation("发送验证码")
    @ApiImplicitParam(name = "phone", value = "电话号码",
            required = true, dataType = "String", paramType = "query", example = "151****9999")
    @GetMapping("/sms")
    public String getSMSCode(@RequestParam String phone){
        Boolean isTrue = PhoneUtil.isMatches(phone);
        if (!isTrue){
            throw new BusinessException(CommonErrorCode.E_200224);
        }

        return iSmsService.sendSms(phone);
    }



    @ApiOperation("注册商户")
    @ApiImplicitParam(name = "merchantRegisterVo", value = "商户注册信息类",
            required = true, dataType = "MerchantRegisterVo", paramType = "body")
    @PostMapping("/merchants/register")
    public MerchantRegisterVo registerMerchant(@RequestBody MerchantRegisterVo merchantRegisterVo) {

        //进行非空校验
        if (merchantRegisterVo.getUsername() == null || "".equals(merchantRegisterVo.getUsername())){
            throw new BusinessException(CommonErrorCode.E_200231);
        }
        if (merchantRegisterVo.getPassword() == null || "".equals(merchantRegisterVo.getPassword())){
            throw new BusinessException(CommonErrorCode.E_200232);
        }
        if (merchantRegisterVo.getMobile() == null || "".equals(merchantRegisterVo.getMobile())){
            throw new BusinessException(CommonErrorCode.E_200230);
        }
        if (merchantRegisterVo.getVerifiykey() == null || "".equals(merchantRegisterVo.getVerifiykey())){
            throw new BusinessException(CommonErrorCode.E_100103);
        }
        if (merchantRegisterVo.getVerifiyCode() == null || "".equals(merchantRegisterVo.getVerifiyCode())){
            throw new BusinessException(CommonErrorCode.E_100103);
        }
        //验证码校验
        Boolean isTrue = iSmsService.checkVerifyCode(merchantRegisterVo.getVerifiyCode(), merchantRegisterVo.getVerifiykey());

        if (!isTrue){
            throw new BusinessException(CommonErrorCode.E_100102);
        }

        MerchantDTO merchantDTO = MerchantCovert.INSTANCE.regMvo2dto(merchantRegisterVo);
        MerchantDTO merchantDTOBack = merchantService.insertMerchant(merchantDTO);

        return MerchantCovert.INSTANCE.dto2regMvo(merchantDTOBack);

    }

    @ApiOperation("商户资质审核")
    @ApiImplicitParam(name = "merchantVo", value = "商户信息", required = true,
                dataType = "MerchantVo", paramType = "body")
    @PostMapping("/my/merchants/save")
    public MerchantVo applyMerchant(@RequestBody MerchantVo merchantVo){

        if (merchantVo.getUsername() == null) {
            throw new BusinessException(CommonErrorCode.E_200231);
        }

        MerchantDTO merchantDTO = MerchantCovert.INSTANCE.vo2dto(merchantVo);
        //从token中获取登录账户的ID
        merchantDTO.setId(SecurityUtil.getMerchantId());
        MerchantDTO result = merchantService.updateMerchant(merchantDTO);
        return MerchantCovert.INSTANCE.dto2vo(result);
    }


    @ApiOperation("文件上传")
    @ApiImplicitParam(name = "file", value = "文件",
            dataType = "MultipartFile", paramType = "body")
    @PostMapping("/upload")
    public String fileUpload(MultipartFile file) {

        if (file == null){
            throw new BusinessException(CommonErrorCode.E_200201);
        }
        String filePath = iFileHandler.fileUpload(file);

        return filePath;

    }

    @ApiOperation("文件下载")
    @ApiImplicitParam(name = "fileName", value = "文件名称",
    required = true, dataType = "String", paramType = "path")
    @GetMapping("/merchants/fileDownload/{fileName}")
    public void fileDownload(@PathVariable("fileName") String fileName){

        iFileHandler.fileDownload(fileName);

    }


    @ApiOperation("分页条件查询商户下门店")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true,
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true,
                    dataType = "int", paramType = "query")})
    @PostMapping("/my/stores/merchants/page")
    public PageVO<StoreDTO> queryStoreByPage(@RequestParam Integer pageNo,
                                            @RequestParam Integer pageSize) {

        Long merchantId = SecurityUtil.getMerchantId();
        QueryStoreDTO queryStoreDTO = new QueryStoreDTO(merchantId, pageNo, pageSize);

        PageVO<StoreDTO> storeDTOS = storeService.queryStoreByPage(queryStoreDTO);


        return storeDTOS;
    }

    /**
     *
     * @param appId 为了获取支付渠道参数
     * @param storeId 门店   商户ID
     * @return
     * @throws BusinessException
     */
    @ApiOperation("生成门店二维码")
    @GetMapping(value = "/my/apps/{appId}/stores/{storeId}/app-store-qrcode")
    public String createCScanBStoreQRCode(@PathVariable String appId,
                                          @PathVariable Long storeId)
            throws BusinessException, IOException {

        //获取商户ID
        Long merchantId = SecurityUtil.getMerchantId();

        //url信息
        QRCodeDto qrCodeDto = new QRCodeDto();
        qrCodeDto.setAppId(appId);
        qrCodeDto.setStoreId(storeId);
        qrCodeDto.setMerchantId(merchantId);
        //二维码URL
        String url = transactionService.createQrURL(qrCodeDto);

        //生成二维码
        QRCodeUtil qrCodeUtil = new QRCodeUtil();
        String qrCode = qrCodeUtil.createQRCode(url, 200, 200);

        return qrCode;
    }

    /**
     * 更新门店信息
     * @param storeVo
     * @return
     */
    @ApiOperation("更新门店信息")
    @ApiImplicitParam(name = "storeVo",value = "门店信息")
    @PutMapping("/my/stores")
    public String addAddress(@RequestBody StoreVo storeVo){

        //前端并没有传递商户id
        if (storeVo.getId() == null){
            throw new BusinessException(CommonErrorCode.E_300002);
        }
        StoreDTO storeDTO = new StoreDTO();
        BeanUtils.copyProperties(storeVo,storeDTO);
        storeService.addAddress(storeDTO);

        return "编辑成功";
    }


    /**
     * 添加员工
     * @param staffVo
     * @return
     */
    @ApiOperation("添加员工")
    @ApiImplicitParam(name = "staffVo",value = "员工信息",dataType = "StaffVo")
    @PutMapping("/my/addStaff")
    public String addStaff(@RequestBody StaffVo staffVo) {

        /**
         * 姓名 用户名 手机号 职位 商店ID
         * 商户Id
         */
        //获取商户ID
        //Long merchantId = SecurityUtil.getMerchantId();
        Long merchantId = 1425055546470539266l;
        //非空校验
        if (staffVo.getFullName() == null || "".equals(staffVo.getFullName())){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        if (staffVo.getUsername() == null || "".equals(staffVo.getUsername())){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        if (staffVo.getMobile() == null || "".equals(staffVo.getMobile())){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        if (staffVo.getStoreId() == null){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        if (staffVo.getPosition() == null || "".equals(staffVo.getPosition())){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        StaffDTO staffDTO = new StaffDTO();
        BeanUtils.copyProperties(staffVo,staffDTO);
        staffDTO.setMerchantId(merchantId);
        //在员工表添加信息
        iStaffService.createStaff(staffDTO);

        return "添加成功";
    }

    /**
     * 编辑员工
     * @param staffVo
     * @return
     */
    @ApiOperation("编辑员工")
    @ApiImplicitParam(name = "staffVo",value = "员工基本信息",dataType = "StaffVo")
    @PutMapping("/my/updateStaff")
    public String updateStaff(@RequestBody StaffVo staffVo) {

        if (staffVo.getId() == null){
            throw new BusinessException(CommonErrorCode.E_200202);
        }

        StaffDTO staffDTO = new StaffDTO();
        BeanUtils.copyProperties(staffVo,staffDTO);
        iStaffService.updateStaff(staffDTO);

        return "操作成功";
    }

    /**
     * 删除员工
     * @param staffId
     * @return
     */
    @ApiOperation("删除员工")
    @ApiImplicitParam(name = "staffId",value = "员工ID")
    @DeleteMapping("/my/deleteStaff")
    public String deleteStaff(Long staffId) {


        if (staffId == null){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        iStaffService.deleteStaff(staffId);
        return "操作成功";
    }

}